/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.user.object.Focus;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.FocusService;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.MD5;
import etcore.webapp.grouptalk.util.StringDisplay;

/**
 * This action validates the request and executes the command of getting my
 * profile,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class MyInfoAction extends AbstractAction {

	private static final long serialVersionUID = -3172975778236417717L;
	// validate result
	public static final int NOT_LOGGED_IN = 0;
	public static final int LOGGED_IN = 1;

	public static final int EDIT_PWD_ALLOWED = 3;
	public static final int ORIGINAL_PWD_ERROR = 4;
	public static final int NEW_PWD_ERROR = 5;

	public static final String CMD_EDIT_PWD = "editUserPwd";
	public static final String CMD_EDIT_GENDER = "editGender";
	public static final String CMD_EDIT_MAIL = "editMail";
	public static final String CMD_EDIT_SIGN = "editSign";
	public static final String CMD_EDIT_AVATAR = "editAvatar";

	// utility constants
	public static final String GROUP_MAP = "groupMap";
	// forward pages

	public static final String MY_PAGE = "/group/myInfo.jsp";

	public static final String ERROR_PAGE = "/error.jsp";

	public static final String LOGIN_PAGE = "/";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(Messages.SESSION_USER);
		String cmd = request.getParameter(PageConstants.CMD);
		if (CMD_EDIT_PWD.equals(cmd) && user != null) {
			String userPwd = request.getParameter("userPwd");
			String userName = request.getParameter("userName");
			UserService userService = new UserService();
			User userPO = userService.findByUserName(userName.trim());
			MD5 md5 = new MD5();
			String oldPwd = md5.getMD5ofStr(userPwd);
			String userNewPwd = request.getParameter("userNewPwd");
			String userNewPwd1 = request.getParameter("userNewPwd1");
			if (!oldPwd.equals(userPO.getPwd())) //
			{
				return ORIGINAL_PWD_ERROR;
			} else if (!userNewPwd.equals(userNewPwd1)) {
				return NEW_PWD_ERROR;
			} else {
				return EDIT_PWD_ALLOWED;
			}
		}

		else {
			if (user != null) {
				return LOGGED_IN;
			}

			return NOT_LOGGED_IN;
		}

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED_IN == validationResult) {
			request.setAttribute("init", "login");
			return LOGIN_PAGE;
		} else if (ORIGINAL_PWD_ERROR == validationResult
				|| NEW_PWD_ERROR == validationResult)
			return ERROR_PAGE;
		return PageConstants.PAGE_PATH_MYINFO;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		editMail(request);
		editGender(request);
		editSign(request);
		editAvatar(request);
		
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		String msg = null;
		if (EDIT_PWD_ALLOWED == validationResult) {

			String userName = request.getParameter("userName");
			UserService userService = new UserService();
			User userPO = userService.findByUserName(userName);
			MD5 md5 = new MD5();
			String userNewPwd = request.getParameter("userNewPwd");
			userPO.setPwd(md5.getMD5ofStr(userNewPwd));
			userService.merge(userPO);

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);

		} else if (ORIGINAL_PWD_ERROR == validationResult) {

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_PWD_ERROR);
			} else {
				msg = Messages.getLabel(Messages.MSG_PWD_ERROR);
			}
			request.setAttribute(Messages.MSG, msg);

		} else if (NEW_PWD_ERROR == validationResult) {
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_NEW_PWD_SAME);
			} else {
				msg = Messages.getLabel(Messages.MSG_NEW_PWD_SAME);
			}
			request.setAttribute(Messages.MSG, msg);
		}

		if (NOT_LOGGED_IN != validationResult) {
			getFollowers(request);
		}
	}

	private void editSign(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		String msg = null;

		User user = (User) session.getAttribute(Messages.SESSION_USER);
		if (CMD_EDIT_SIGN.equals(cmd) && user != null) {

			String sign = request.getParameter("sign");

			UserService userService = new UserService();

			if (sign != null)
				user.setSign(sign);
			userService.merge(user);

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);

		}
	}

	private void editGender(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		String msg = null;

		User user = (User) session.getAttribute(Messages.SESSION_USER);
		if (CMD_EDIT_GENDER.equals(cmd) && user != null) {
			String gender = request.getParameter("gender");

			UserService userService = new UserService();

			user.setGender(gender);

			userService.merge(user);

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);

		}
	}

	private void editAvatar(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		String msg = null;

		User user = (User) session.getAttribute(Messages.SESSION_USER);
		if (CMD_EDIT_AVATAR.equals(cmd) && user != null) {
			String email = request.getParameter("avatar");

			UserService userService = new UserService();

			if (email != null && email.length() > 4 && email.indexOf("@") != -1)
				user.setEmail(email.trim());

			userService.merge(user);

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);

		}
	}

	private void editMail(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		String msg = null;
		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		User user = (User) session.getAttribute(Messages.SESSION_USER);
		if (CMD_EDIT_MAIL.equals(cmd) && user != null && isAdmin) {
			String email = request.getParameter("userEmail");

			UserService userService = new UserService();

			if (email != null && email.length() > 4 && email.indexOf("@") != -1)
				user.setEmail(email.trim());

			userService.merge(user);

			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);

		}
	}

	private void getFollowers(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(Messages.SESSION_USER);
		if (user == null)
			return;
		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		String part = request.getParameter("part");
		Map<Object, Object> groupMap = new HashMap<Object, Object>();
		FocusService focusService = new FocusService();
		MessageService msgService = new MessageService();
		GroupService groupService = new GroupService();
		UserService userService = new UserService();

		if ("groups".equals(part) || part == null) {
			List<Group> myGroups = groupService.findFollowingGroups(
					user.getUserName(), 0, 20);
			request.setAttribute("myGroups", myGroups);
		}
		if ("following".equals(part) || part == null) {
			List<Focus> following = focusService.findByProperty("fromUser",
					user.getUserName(), 0, 20);
			request.setAttribute("following", following);
			if (following != null) {
				for (Focus focus : following) {
					String toUser = focus.getToUser();
					User checkUser = userService.findByUserName(toUser);
					if (checkUser != null)
						request.setAttribute(toUser + "Signature",
								checkUser.getCode());
					@SuppressWarnings("rawtypes")
					List msgs = null;
					if (isAdmin) {
						msgs = msgService.findByProperty(
								PageConstants.USERNAME, toUser, 0, 3);

					} else {
						msgs = msgService.findPublicMessages(
								PageConstants.USERNAME, toUser, 0, 3);
					}

					@SuppressWarnings("rawtypes")
					Iterator iterator = msgs.iterator();
					while (iterator.hasNext()) {
						Object[] tempm = (Object[]) iterator.next();
						Integer tempm_id = (Integer) tempm[0];
						String tempm_source = (String) tempm[9];
						String tempm_stime = (String) tempm[10];
						Group group = groupService.findGroupByGmid(tempm_id);
						if (group != null)
							groupMap.put(tempm_id, group);
						if (group.getOpen() == 4) {
							StringBuffer reminderDate = StringDisplay
									.getReminderDateStringBuffer(tempm_source,
											tempm_stime);
							request.setAttribute(tempm_id + "reminderDate",
									reminderDate.toString());
						}
					}

					request.setAttribute(toUser + PageConstants.MSGS, msgs);
				}

			}
		}
		if ("followers".equals(part) || part == null) {
			List<Focus> followed = focusService.findByProperty("toUser",
					user.getUserName(), 0, 20);
			request.setAttribute("followers", followed);
			if (followed != null) {
				for (Focus focus : followed) {
					String fromUser = focus.getFromUser();
					User checkUser = userService.findByUserName(fromUser);
					if (checkUser != null)
						request.setAttribute(fromUser + "Signature",
								checkUser.getCode());
					@SuppressWarnings("rawtypes")
					List msgs = null;
					if (isAdmin) {
						msgs = msgService.findByProperty(
								PageConstants.USERNAME, fromUser, 0, 3);

					} else {
						msgs = msgService.findPublicMessages(
								PageConstants.USERNAME, fromUser, 0, 3);
					}

					@SuppressWarnings("rawtypes")
					Iterator iterator = msgs.iterator();
					while (iterator.hasNext()) {
						Object[] tempm = (Object[]) iterator.next();
						Integer tempm_id = (Integer) tempm[0];
						String tempm_source = (String) tempm[9];
						String tempm_stime = (String) tempm[10];
						Group group = groupService.findGroupByGmid(tempm_id);
						if (group != null)
							groupMap.put(tempm_id, group);
						if (group.getOpen() == 4) {
							StringBuffer reminderDate = StringDisplay
									.getReminderDateStringBuffer(tempm_source,
											tempm_stime);
							request.setAttribute(tempm_id + "reminderDate",
									reminderDate.toString());
						}
					}

					request.setAttribute(fromUser + PageConstants.MSGS, msgs);
				}

			}
		}
		request.setAttribute(GROUP_MAP, groupMap);
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces=new ArrayList<String>();
		namespaces.add(MessageNamespaces.MY_PROFILE);
		return namespaces;
	}

}
